<template>
  <div class="container">
    <el-page-header @back="goBack" content="地区库设置"></el-page-header>

    <el-row type="flex" justify="space-between" class="nav-bar">
      <el-col :span="3" class="buttonList">
        <!-- <el-button type="primary" @click="create" v-show="utils.checkAdminPermission('系统设置.地区库设置.新建')">新建</el-button> -->
        <el-button type="primary" icon="el-icon-plus" plain @click="create">新建</el-button>
        <!-- <el-button type="primary" @click="lastCity" v-if="currentCity.level > 0">返回上一级</el-button> -->
      </el-col>
      <el-col class="text-right">
        <el-form :inline="true" label-width="auto" class="nav-bar-form">
          <el-form-item>
            <el-input placeholder="关键词搜索" v-model="key" clearable prefix-icon="el-icon-search" @clear="getList">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList(currentCity.id)">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 导航 -->
    <div class="breadcrumb-box flex e-m-b-10" v-if="breadcrumbList.length > 0">
        <span style="font-size: 14px;line-height: 1;" class="tips">地区导航：</span>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="e-m-b-10">
            <el-breadcrumb-item 
                v-for="(item, index) in breadcrumbList" 
                :key="index"
                @click.native="handleBreadcrumbClick(item, index)"
                :class="{ 'is-last': index === breadcrumbList.length - 1 }"
            >
                
                <el-link type="primary">{{ item.name }}</el-link>
            </el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <el-table :data="tableData" style="width: 100%" stripe>
      <el-table-column prop="name" label="名称">
      </el-table-column>
      <!-- <el-table-column prop="english" label="英文" width="300">
      </el-table-column> -->
      <el-table-column prop="sort" label="排序" width="200">
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button @click="next(scope.row)" type="text" size="small">下级</el-button>
          <el-button @click="edit(scope.row)" type="text" size="small"
            v-show="utils.checkAdminPermission('系统设置.地区库设置.编辑')">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination">
      <el-pagination background layout="sizes, total, prev, pager, next" :total="total" :page-sizes="[10, 50, 100, 200]"
        :page-size="pageSize" :current-page="page" @current-change="pageChange" @size-change="handleSizeChange">
      </el-pagination>
    </div>
    <el-dialog :title="dialogType == 0 ? '新建地区库' : '编辑地区库'" :visible.sync="dialogVisible" width="500px">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="下级地区" prop="name" v-if="areas.length > 0">
          <el-select v-model="form.name" placeholder="请选择" filterable clearable>
            <el-option value="">-请选择-</el-option>
            <el-option v-for="area in areas" :value="area.name" :key="area.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="填写地区名" prop="name" v-else>
          <el-input placeholder="填写地名" v-model="form.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  mapState
} from 'vuex';

export default {
  layout: 'admin',
  head() {
    return {
      title: '地区库设置-' + this.websetting.name
    }
  },
  data() {
    return {
      // 面包屑导航数组
      breadcrumbList: [
          // {
          //     name: '一级类型',
          //     pid: 0
          // }
      ], 
      categoryTypeObj: {},

      currentCity: {
        pid: 0,
        id: 0,
        level: 0,
        code: [],
        path: [],
        names: []
      },
      key: '',
      page: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      dialogVisible: false,
      dialogType: 0, //0：创建	1：编辑
      areas: [],
      form: {
        pid: 0,
        name: '',
        code: ''
      },
      districtSearch: null
    }
  },
  computed: {
    ...mapState({
      loading: state => state.loading,
      operator: state => state.operator
    }),
  },
  mounted() {
    // 初始化地区（指定经营地区，从/Operator/Detail获取）
    this.$axios.get('/Operator/Detail').then((res)=>{
      let setCity = res.city
      this.breadcrumbList.push({
          id: setCity.cityid,
          name: setCity.cityname,
          pid: setCity.citypath.split(",").filter((item)=>item != "")[0],
          path: setCity.citypath,
          code: setCity.citycode || '441800',
          level: 1
      })
      this.currentCity.id = setCity.cityid
      this.getList(setCity.cityid);
    })
    // this.breadcrumbList = [
    //     {
    //         name: '全国',
    //         id: 0,
    //         pid: 0,
    //         level: 0
    //     }
    // ]
    // this.getList(0);
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    // 点击面包屑项
    handleBreadcrumbClick(item, index) {
        this.currentCity.code.push(item.code);
        this.currentCity.path.push(item.id.toString());
        this.currentCity.names.push(item.name);
        this.currentCity.id = item.id;
        this.currentCity.level = item.level
        // 点击的不是最后一项时才允许跳转
        if(index < this.breadcrumbList.length - 1) {
            // 如果是根节点
            if(index === 0) {
                this.getList(item.id)
                this.breadcrumbList = this.breadcrumbList.slice(0, 1)
            } else {

                // 这里需要根据你的接口实现获取父级数据
                this.getList(item.id,item) 
                this.breadcrumbList = this.breadcrumbList.slice(0, index + 1)
            }
        }
    },
    // 获取地区列表
    getList(pid,categoryTypeObj) {
      console.log('this.operator', this.operator)
      if(categoryTypeObj){
          this.categoryTypeObj = categoryTypeObj
      }else{
          this.categoryTypeObj = {}
      }
      // 当进入下级时更新面包屑
      if(pid > 0 && categoryTypeObj) {
          this.breadcrumbList.push({
              ...categoryTypeObj
          })
      }
      return this.$axios.post('/city/list', {
        "PageIndex": this.page,
        "PageSize": this.pageSize,
        "Key": this.key,
        "pId": pid || this.currentCity.id
      }).then((res) => {
        this.tableData = res.rows;
        this.total = res.total;

        return res;
      })
    },
    pageChange(e) { // 页码切换事件
      this.page = e;
      this.getList()
    },
    handleSizeChange(val) {
      this.page = 1;
      this.pageSize = val;
      this.getList()
    },
    next(item) {
      this.currentCity.level += 1;
      this.currentCity.code.push(item.code);
      this.currentCity.path.push(item.id.toString());
      this.currentCity.names.push(item.name);
      this.currentCity.id = item.id;
      this.page = 1;
      this.key = "";
      this.getList(item.id,item);
    },
    create() {
      var that = this;
      this.$AMapLoader.load({
        key: this.AMapSetting.key,             // 申请好的Web端开发者Key，首次调用 load 时必填
        version: this.AMapSetting.version,      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.DistrictSearch'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {

        if (this.districtSearch == null) {
          //行政区划查询
          var opts = {
            subdistrict: 1, //返回下一级行政区
            showbiz: false, //最后一级返回街道信息
          };

          this.districtSearch = new AMap.DistrictSearch(opts); //注意：需要使用插件同步下发功能才能这样直接使用
          console.log(this.districtSearch);
        };

        let searchKeyword = this.breadcrumbList[this.breadcrumbList.length - 1].code
        if(searchKeyword){
          this.districtSearch.search(searchKeyword, (status, result) => {
            if (status == 'complete') {
              console.log('this.currentCity.level', this.currentCity.level)
              console.log('searchKeyword', searchKeyword)
              console.log('districtSearch.search', result);
              that.getData(result.districtList[0]);
            }
            if(status == 'no_data'){
              this.areas = []
            }
          });
        }else{
          that.getData({districtList:[]});
        }
        
        this.form.pid = this.currentCity.id;
        //this.form.id = 0;
        this.form.name = '';
        this.dialogType = 0;

        // if(!searchKeyword){
        //   this.areas = []
        // }

        this.dialogVisible = true;
      })
    },
    // 获取地区列表（从高度地图api获取）
    getData(data) {
      this.areas.length = 0;
      this.form.name = "";

      var subList = data.districtList;
      if (subList) {
        for (var i = 0, l = subList.length; i < l; i++) {
          this.areas.push({
            name: subList[i].name,
            code: subList[i].adcode
          });
        }
      }else{
        this.areas.length = 0
      }
    },
    edit(row) {
      this.form.id = row.id;
      this.form.name = row.name;
      this.form.english = row.english;
      this.form.ishot = row.ishot;
      this.dialogType = 1;
      this.dialogVisible = true;
    },
    submit() {
      for (var i = 0, l = this.areas.length; i < l; i++) {
        if (this.form.name == this.areas[i].name)
          this.form.code = this.areas[i].code;
      }
      // this.form.code = this.currentCity.code;
      this.$axios.post('/city/' + (this.dialogType == 0 ? 'create' : 'edit'), this.form).then((res) => {
        this.$message.success(res.msg);
        this.dialogVisible = false;
        this.getList();
      })
    }
  }
}
</script>

<style lang="scss" scoped="">
.nav-bar {
  margin-top: 20px;

  .buttonList {
    display: flex;
    height: 40px;
  }
}
</style>
